<template>
  <div>
    <time-line>
      <time-line-item
        v-for="commment in list"
        :key="commment.id"
        :label="commment.create_at | formatDate"
        :header="commment.user_name"
        :body="commment.content"
        theme="blue" />
    </time-line>
    <el-form ref="form" :model="formData" class="comment-form">
      <el-form-item label="">
        <el-input v-model="formData.content" :rows="5" type="textarea" placeholder="添加评论"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitComment">发表评论</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import moment from 'moment'
import TimeLine from '@/components/TimeLine'
import TimeLineItem from '@/components/TimeLine/TimeLineItem'
import { getList as getComments, publishComment } from '@/api/comment'

moment.locale('zh-cn')

export default {
  components: {
    TimeLine,
    TimeLineItem
  },
  filters: {
    formatDate(dateStr) {
      return moment(dateStr).fromNow()
    }
  },
  props: {
    docId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      total: 0,
      page: 1,
      pageSize: 20,
      formData: {
        content: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      console.log(this.docId)
      getComments({ docId: this.docId }).then(res => {
        this.list = res
      })
    },
    getQuery(kvpairs) {
      const params = {
        limit: this.pageSize,
        offset: (this.page - 1) * this.pageSize
      }
      Object.assign(params, kvpairs)
      return params
    },
    onSubmitComment() {
      const params = Object.assign({
        docId: this.docId
      }, this.formData)
      publishComment(params).then(res => {
        this.$message({
          message: '评论发表成功',
          type: 'success'
        })
        this.fetchData()
        this.formData.content = ''
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .comment-form {
    margin-top: 50px;
    @media screen and (min-width: 992px) {
      width: 50%;
    }
  }
</style>
